package com.cn.springcloudwechat.common.utils.weixin.util;

import java.net.URLEncoder;
import java.util.*;


public  class WxUtil {
	public static String CreateNoncestr() {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < 16; i++) {
			Random rd = new Random();
			res += chars.charAt(rd.nextInt(chars.length() - 1));
		}
		return res;
	}
	public static long getUnixTime(Date date) {
		if (null == date) {
			return 0;
		}

		return date.getTime() / 1000;
	}
	public static String  formatBizQueryParaMap(HashMap<String, String> paraMap,
			boolean urlencode) throws Exception {

		String buff = "";
		try {
			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(
					paraMap.entrySet());

			Collections.sort(infoIds,
					new Comparator<Map.Entry<String, String>>() {
						public int compare(Map.Entry<String, String> o1,
								Map.Entry<String, String> o2) {
							return (o1.getKey()).toString().compareTo(
									o2.getKey());
						}
					});

			for (int i = 0; i < infoIds.size(); i++) {
				Map.Entry<String, String> item = infoIds.get(i);
				// System.out.println(item.getKey());
				if (item.getKey() != "") {

					String key = item.getKey();
					String val = item.getValue();
					if (urlencode) {
						val = URLEncoder.encode(val, "utf-8");

					}
					buff += key + "=" + val + "&";

				}
			}

			if (buff.isEmpty() == false) {
				buff = buff.substring(0, buff.length() - 1);
			}
		} catch (Exception e) {
			throw  e;
		}
		return buff;
	}

	public static String  getSignBySha1(HashMap<String, String> params)
			throws Exception 	{
		// 格式化参数
		String sign =WxUtil.formatBizQueryParaMap(params, false);

		// MD5加密 & 所有字符转换为大写
		// System.out.println(sign);
		sign = Sha1Util.getSha1(sign).toUpperCase();
		// System.out.println("sign:"+sign);
		//
		return sign;
	}
}
